<?php

namespace App\Models;


class Worker extends BaseModel
{
    protected $table = "worker";
    protected $redisTable = "worker";
    protected $redisTableList = "worker_list";
    protected $rules = [
        'code' => 'required|regex:/\w{4,6}/|unique:worker,code',
        'name' => 'required|between:1,5',
        'mobile' => 'required|regex:/^1[34578]{1}\d{9}$/',
        'admin_id' => 'required',
        'shop_id' => 'required',
//        'mid' => 'required|numeric',
    ];

    protected $message = [
        'code.required' => '工号必须填写',
        'code.regex' => '工号必须是4-6位数字或字母',
        'code.unique' => '该工号已存在，请重新输入',
        'name.required' => '姓名必须填写',
        'name.between' => '姓名不能超过5个字',
        'mobile.required' => '手机号必须填写',
        'mobile.regex' => '请输入正确的手机号',
        'admin_id.required' => '获取商户信息失败',
        'shop_id.required' => '获取店铺信息失败',
//        'mid.required' => '请输入用户ID',
//        'mid.numeric' => '用户ID必须是纯数字',
    ];

    public function getWorkerList()
    {
        $keyword = request('keyword');
        $where['admin_id'] = plat_admin_id();
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['code'] = $keyword;
            } else {
                $where['name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $rows = $this->_getPageList($where);
        $txtStr['import_auth'] = [1 => '开启', 0 => '关闭'];
        $txtStr['charge_auth'] = [1 => '开启', 0 => '关闭'];
        $txtStr['recover_auth'] = [1 => '开启', 0 => '关闭'];
        $txtStr['creat_order_auth'] = [1 => '开启', 0 => '关闭'];
        $txtStr['order_resend_auth'] = [1 => '开启', 0 => '关闭'];
        $txtStr['status'] = [1 => '正常', 0 => '禁用'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getOwnWorkerList($shopId)
    {
        $keyword = request('keyword');
        $where['admin_id'] = plat_admin_id();
        $where['shop_id'] = $shopId;
        $pageLength = 5;
        $pageSize = 15;

        $rows = $this->where("admin_id", plat_admin_id())->where('shop_id', $shopId);
        if ($keyword) {
            $rows = $rows->where(function($query)use($keyword){
                $query->where('name', 'like', "%{$keyword}%")
                    ->orWhere('code', 'like', "%{$keyword}%");
            });
        }
        $rows = $rows->paginate($pageSize)->appends([
            'keyword' => $keyword
        ]);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), $pageLength);
        }
        $txtStr['import_auth'] = [1 => '开启', 0 => '关闭'];
        $txtStr['charge_auth'] = [1 => '开启', 0 => '关闭'];
        $txtStr['recover_auth'] = [1 => '开启', 0 => '关闭'];
        $txtStr['creat_order_auth'] = [1 => '开启', 0 => '关闭'];
        $txtStr['order_resend_auth'] = [1 => '开启', 0 => '关闭'];
        $txtStr['status'] = [1 => '正常', 0 => '禁用'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }


    public function addOrUpdate($shopId)
    {
        $data['name'] = trim(request('name'));
        $data['mobile'] = trim(request('mobile'));
        $data['code'] = trim(request('code'));
        $data['import_auth'] = request('import_auth', 0);
        $data['charge_auth'] = request('charge_auth', 0);
        $data['recover_auth'] = request('recover_auth', 0);
        $data['creat_order_auth'] = request('creat_order_auth', 0);
        $data['order_resend_auth'] = request('order_resend_auth', 0);
        $data['max_order_num'] = request('max_order_num', 99);
        $data['pwd'] = md5(123456);
        $data['admin_id'] = plat_admin_id();
        $data['shop_id'] = $shopId;
//        $data['mid'] = trim(request('mid'));
        if (request('id')) {
            $data['id'] = trim(request('id'));
            $this->rules['code'] .= ',' . $data['id'] . ',id';
            unset($data['pwd']);
            if (request('pwd')) {
                $data['pwd'] = md5(trim(request('pwd')));
            }
        }
//        if (request('id')) {
//            $data['id'] = trim(request('id'));
//            $this->rules['mobile'] .=  ','.$data['id'].',id'.',admin_id,'.$data['admin_id'].',shop_id,'.$data['shop_id'];
//            $this->rules['code'] .=  ','.$data['id'].',id'.',admin_id,'.$data['admin_id'].',shop_id,'.$data['shop_id'];
//            unset($data['pwd']);
//            if (request('pwd')) {
//                $data['pwd'] = md5(trim(request('pwd')));
//            }
//        } else {
//            $this->rules['mobile'] .=  ','.NULL.','.NULL.',admin_id,'.$data['admin_id'].',shop_id,'.$data['shop_id'];
//            $this->rules['code'] .=  ','.NULL.','.NULL.',admin_id,'.$data['admin_id'].',shop_id,'.$data['shop_id'];
//        }
        if (!$this->_validate($data)) {
            return false;
        }
//        $member = new Member();
//        $memberInfo = $member->_getOne(['id' => $data['mid'], 'admin_id' => plat_admin_id()]);
//        if (!$memberInfo) {
//            $this->error = '该用户ID不存在!';
//            return false;
//        }
//        $worker = $this->_getOne(['mid' => $data['mid']]);
//        if ($worker) {
//            $this->error = '该用户ID下拥有送水工信息，无法绑定';
//            return false;
//        }
//        $data['xcx_openid'] = $memberInfo['xcx_openid'];
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '保存失败!';
            return false;
        }
        $this->_redisGenerate($res);
        if (!request('id')) {
            $this->_redisGenerateList($shopId);
        }
        return $res;
    }

    public function move()
    {
        $admin_id = request('aid');
        $data['id'] = trim(request('wid'));
        $data['name'] = trim(request('name'));
        $data['mobile'] = trim(request('mobile'));
        if (!$data['id']) {
            $this->error = '请输入迁移人ID';
            return false;
        }
        if (!$data['name']) {
            $this->error = '请输入迁移人姓名';
            return false;
        }
        if (!$data['mobile']) {
            $this->error = '请输入迁移人手机号';
            return false;
        }
        if (!is_mobile($data['mobile'])) {
            $this->error = '请输入正确手机号';
            return false;
        }
        $data['mid'] = trim(request('move_id'));
        $worker = $this->_getOne(['mid' => $data['mid']]);
        if ($worker) {
            $this->error = '该迁移人ID下拥有送水工信息，无法迁移';
            return false;
        }
        $member = new Member();
        $memberInfo = $member->_getOne(['id' => $data['mid'], 'admin_id' => $admin_id]);
        if (!$memberInfo) {
            $this->error = '该用户ID不存在!';
            return false;
        }
        $data['xcx_openid'] = $memberInfo['xcx_openid'];
        $data['pwd'] = md5(123456);
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '迁移失败!';
            return false;
        }
        return $res;
    }

    /**
     * 用户登录认证
     */
    public function login()
    {
        $username = request('username');
        $pwd = request('pwd');
        if (!($username && $pwd)) {
            $this->error = '请输入账号和密码!';
            return false;
        }
        $where['pwd'] = md5($pwd);
//        if (strlen($username) == 4) {
        $where['code'] = trim($username);
//        }
//        if (is_mobile($username)) {
//            $where['mobile'] = trim($username);
//        }
        $worker = $this->_getOne($where);
        if (!$worker) {
            $this->error = '账号或密码错误!';
            return false;
        }
        if (!$worker['status']) {
            $this->error = '该账号已被禁用!';
            return false;
        }
        $shop = new Shop();
        $shopInfo = $shop->_redisGetOneBySid($worker['shop_id']);
        $this->_redisGetOneByWid($worker['id']);
        return ['wid' => $worker['id'], 'aid' => $worker['admin_id'], 'sid' => $worker['shop_id'], 'shop_name' => $shopInfo['shop_name'], 'name' => $worker['name'], 'openid' => $worker['openid']];
    }

    public function modifyPwd()
    {
        $id = trim(request('wid'));
        $oldpwd = trim(request('oldpwd'));
        $pwd = trim(request('pwd'));
        $repwd = trim(request('repwd'));
        if (!$id) {
            $this->error = '非法操作!';
            return false;
        }
        if (!$oldpwd) {
            $this->error = '请输入原始密码!';
            return false;
        }
        if (!($pwd && $repwd)) {
            $this->error = '请输入新密码和重复密码!';
            return false;
        }
        if ($pwd != $repwd) {
            $this->error = '新密码和重复密码不一致!';
            return false;
        }
        $where['id'] = $id;
        $where['pwd'] = md5($oldpwd);
        $worker = $this->_getOne($where);
        if (!$worker) {
            $this->error = '原始密码错误!';
            return false;
        }
        $data['id'] = $id;
        $data['pwd'] = md5($pwd);
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '修改密码失败!';
            return false;
        }
        $this->_redisGenerate($id);
        return '修改密码成功!';
    }

    public function searchMember()
    {
        $keyword = request('keyword');
        $where['shop_id'] = request('sid');
        if (!$keyword) {
            $this->error = '请输入手机号或地址!';
            return false;
        }
        if (is_numeric($keyword)) {
            $where['mobile'] = ['like', '%' . trim($keyword) . '%'];
        } else {
            $where['address'] = ['like', '%' . trim($keyword) . '%'];
        }
        $address = new Address();
        $res = $address->_getList($where, 'mid as id,name,mobile,address')->toArray();
        return $res;
    }

    public function _redisGenerate($wid)
    {
        $table = $this->redisTable;
        $key = $wid;
        $this->redis->hdel($table, $key);
    }

    public function _redisGenerateList($sid)
    {
        $table = $this->redisTableList;
        $key = $sid;
        $this->redis->hdel($table, $key);
    }

    public function _redisGetOneByWid($wid)
    {
        $table = $this->redisTable;
        $key = $wid;
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            if ($res) {
                return unserialize($res[0]);
            }
        }
        $info = '';
        $res = $this->_getOneById($wid);
        if ($res) {
            $info = $res->toArray();
            $this->redis->hmset($table, [$key => serialize($info)]);
        }
        return $info;
    }

    public function _redisGenerateByIds($ids)
    {
        $table = $this->redisTable;
        foreach ($ids as $v) {
            $key = $v;
            $this->redis->hdel($table, $key);
        }

    }

    public function _redisGetWorkerList($sid)
    {
        $table = $this->redisTableList;
        $key = $sid;
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            if ($res) {
                return unserialize($res[0]);
            }
        }
        $res = $this->_getList(['shop_id'=>$sid],'id');
        $info = '';
        if ($res) {
            $info = $res->toArray();
            $this->redis->hmset($table, [$key => serialize($info)]);
        }
        return $info;
    }

    public function bindWx()
    {
        $id = trim(request('wid'));
        $openid = trim(request('openid'));
        if (!$id) {
            $this->error = '非法操作!';
            return false;
        }
        if (!$openid) {
            $this->error = '未获取到微信信息!';
            return false;
        }
        $where['id'] = $id;
        $worker = $this->_getOne($where);
        if (!$worker) {
            $this->error = '非法操作!';
            return false;
        }
        if ($worker['openid']) {
            $this->error = '该送水工已绑定微信信息!';
            return false;
        }
        $data['id'] = $id;
        $data['openid'] = $openid;
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '绑定微信失败!';
            return false;
        }
        $this->_redisGenerate($id);
        $this->_redisGetOneByWid($id);
        return '绑定微信成功!';
    }


    public function recoverBucket()
    {
        $shopId = request('sid');
        $workerId = request('wid');
        $adminId = request('aid');
        $mid = request('mid');
        $bucket_nums = request('nums', []);
        $bucket_category_ids = request('bucket_category_ids', []);
        $bucket_nums = array_filter($bucket_nums);
        if (!$mid) {
            $this->error = '非法操作！';
            return false;
        }
        foreach ($bucket_nums as &$v) {
            if (!is_numeric($v)) {
                $this->error = '请输入正确的回桶数量！';
                return false;
            }
        }
        if (array_sum($bucket_nums) > 0) {
            if (!$bucket_category_ids) {
                $this->error = '请选择水桶品牌！';
                return false;
            }
            $bucket_category_ids = array_filter($bucket_category_ids);
            foreach ($bucket_category_ids as &$v) {
                if ($v < 1) {
                    $this->error = '请选择水桶品牌！';
                    return false;
                }
            }
        }
        $member = new Member();
        $memberInfo = $member->_getOneById($mid, 'name,initial_bucket_num,total_bucket_num,total_back_bucket_num,cash_bucket_num');
        if (!$memberInfo) {
            $this->error = '非法操作！';
            return false;
        }
        $num = array_sum($bucket_nums);
        $time = time();
        $formatTime = date('Y-m-d H:i:s');
        $logData = [
            'order_id' => 0,
            'shop_id' => $shopId,
            'worker_id' => $workerId,
            'buyer_id' => $mid,
            'buyer_name' => $memberInfo['name'],
            'send_num' => 0,
            'bucket_num' => $num,
            'description' => '零送水取桶',
            'addtime' => $time,
            'created_at' => $formatTime,
            'updated_at' => $formatTime,
        ];
        $this->_start();
        try {
//                tolog('logData');
//                tolog($logData);
            $bucketLog = new BucketLog();
            $logId = $bucketLog->_insert($logData); //(8)
            $bucketData = new BucketData();
            $buckeLogIn = new BucketLogIn();
            $backLogData = new BackLogData();
            if ($num && !empty($bucket_nums) && !empty($bucket_category_ids) && count($bucket_nums) == count($bucket_category_ids)) {
                foreach ($bucket_nums as $k => $v) {
                    $bData = [
                        'bucket_num_in' => "`bucket_num_in` + $v",
                        'bucket_num_out' => "`bucket_num_out` - $v",
                    ];
                    $where['shop_id'] = $shopId;
                    $where['bucket_category_id'] = $bucket_category_ids[$k];
//                        tolog('where');
//                        tolog($where);
//                        tolog('bData');
//                        tolog($bData);
                    $a = $bucketData->_updateOrigin($where, $bData); //(6)
//                        tolog('i---' . $a);
                    $backData[] = [
                        'shop_id' => $shopId,
                        'worker_id' => $workerId,
                        'buyer_id' => $mid,
                        'order_id' => 0,
                        'log_id' => $logId,
                        'bucket_category_id' => $bucket_category_ids[$k],
                        'num' => $v,
                        'type' => 1,
                        'created_at' => $formatTime,
                        'updated_at' => $formatTime,
                    ];
                    //记录店内水桶日志 type:1.店内期初+ 2.进货入桶+ 3.进货回桶- 4.新购水桶+ 5.售出水桶- 6.送桶- 7.回桶+
                    $a = $buckeLogIn->addLog($adminId, $shopId, $bucket_category_ids[$k], $v,0,$workerId, 8);
//                        tolog('buckeLogIn_8---' . $a);
                }
            }
            if (!empty($backData)) {
                foreach ($backData as &$v) {
                    $v['log_id'] = $logId;
                }
                $m = $backLogData->_add($backData);
//                tolog('backLogData---' . $a);
            }
            $a = $this->_inc(['id' => $workerId], 'total_back_bucket_num', $num);//(5)
//            tolog('worker---' . $a);
            $total_bucket_num = $memberInfo['total_bucket_num'];
            $total_back_bucket_num = $memberInfo['total_back_bucket_num'] + $num;
            $memberData = [
                'total_back_bucket_num' => $total_back_bucket_num,
                'borrow_bucket_num' => $memberInfo['initial_bucket_num'] + $total_bucket_num - $total_back_bucket_num - $memberInfo['cash_bucket_num'],
            ];
//                    tolog('memberData');
//                    tolog($memberData);
            $a = $member->_update(['id' => $mid], $memberData);//(3)
//            tolog('member---' . $a);
            $this->_commit();
            return '操作成功';
        } catch (\Exception $e) {
            $this->_rollBack();
            $this->error = '提交数据不完整，请重新提交!';
            return false;
        }
    }

    public function removeBindWx($wid)
    {
        if (!$wid) {
            $this->error = '非法操作!';
            return false;
        }
        $res = $this->_getOneById($wid,'openid');
        if (!$res) {
            $this->error = '非法操作!';
            return false;
        }
        if (!$res['openid']) {
            $this->error = '非法操作!';
            return false;
        }
        $res = $this->_update(['id'=>$wid],['openid'=>'']);
        if (!$res) {
            $this->error = '操作失败!';
            return false;
        }
        $this->_redisGenerate($wid);
        return '操作成功';
    }

    public function checkMaxOrderNum($wid)
    {
        $table = 'worker_order_num_list';
        $key = $wid;
        $num = 0;
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            if (!empty($res)) {
                $num = intval($res[0]);
            }
        } else {
            $num = 1;
            $this->redis->hmset($table, [$key => $num]);
        }
        $workerInfo = $this->_redisGetOneByWid($wid);
        $max_order_num = $workerInfo['max_order_num'];
        if ($num >= $max_order_num) {
            $this->error = '已达接单上限，最多只能接'.$max_order_num.'单';
            return false;
        }
        return true;
    }

    public function _redisChangeMaxOrderNum($wid,$num = 1)
    {
        $table = 'worker_order_num_list';
        $key = $wid;
        $workerInfo = $this->_redisGetOneByWid($wid);
        $max_order_num = $workerInfo['max_order_num'];
        if ($this->redis->hexists($table, $key)) {
            $nowNum = 0;
            $res = $this->redis->hmget($table, $key);
            if (!empty($res)) {
                $nowNum = intval($res[0]);
            }
            if (($nowNum + $num) < $max_order_num) {
                $this->redis->hincrby($table, $key, $num);
            }
        } else {
            $this->redis->hmset($table, [$key => $num]);
        }
    }

}
